<script setup>
import { ref } from 'vue';
import { userLoginApi } from '../../api/user';

const userInfo = ref({
    avatarUrl: '',
    nickName: 'test'
})

const wxData = ref({
	iv: '',
	encryptedData: ''
});

const login = () => {
	if(!wxData.value.iv || !wxData.value.encryptedData) {
		uni.showToast({
			title: '请获取手机号',
			icon: 'error'
		});
		return;
	}
    uni.getProvider({
    	service: 'oauth',
		success: (res) => {
			if(!res.provider.includes('weixin')) {
				uni.showToast({
					title: '微信授权失败',
					icon: 'error'
				});
				return;
			}
			
			uni.getUserProfile({
				desc: '获取你的昵称、头像地区及性别',
				success: (info) => {
					uni.login({
						provider: 'weixin',
						success: async (res) => {
							console.log('data', {
								avatar: info.userInfo.avatarUrl,
								name: info.userInfo.nickName,
								iv: wxData.value.iv,
								encryptedData: wxData.value.encryptedData,
								code: res.code
							});
							try {
								const results = await userLoginApi({
									avatar: info.userInfo.avatarUrl,
									name: info.userInfo.nickName,
									iv: wxData.value.iv,
									encryptedData: wxData.value.encryptedData,
									code: res.code
								});
							} catch (error) {
								console.error('userLogin error', error);
								uni.showToast({
									title: '登录失败',
									icon: 'error'
								});
							}
						},
						fail: (error) => {
							console.error('login error', error);
							uni.showToast({
								title: '微信登录失败',
								icon: 'error'
							});
						}
					})
				},
				fail: (error) => {
					console.error('getUserProfile error', error);
					uni.showToast({
						title: '获取个人信息失败',
						icon: 'error'
					});
				}
			})
		},
		fail: (error) => {
			console.error('getProvider error', error);
			uni.showToast({
				title: '微信授权失败',
				icon: 'error'
			});
		}
    })
};

const phoneLogin = (event) => {
	wxData.value.iv = event.detail.iv;
	wxData.value.encryptedData = event.detail.encryptedData;
}

</script>

<template>
    <view class="app-login">
        <!-- <view style="width: 200rpx; height: 80rpx; background-color: red; color: white;" @click="login">登录</view> -->
        <text>123</text>
		<button open-type="getUserInfo" @click="login">登录</button>
        <button open-type="getPhoneNumber" @getphonenumber="phoneLogin">获取手机号</button>
        <view v-if="userInfo">
            <image :src="userInfo.avatarUrl" class="avatar"></image>
            <text>{{ userInfo.nickName }}</text>
        </view>
        <text>456</text>
    </view>
</template>

<style src="./style.scss" scoped />